<?php

/**
 * alltosun.com 主控制器 Controller.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 高竞竞 (gaojj@alltosun.com) $
 * $Date: 2010-12-28 下午03:29:31 $
*/

abstract class Controller
{
    /**
     * 控制器实例
     */
    private static $actionInstance = null;

    /**
     * 控制器分派
     */
    public static function dispatch()
    {
        // ip禁止访问
        /*
        if (_widget('ip')->is_ban()) {
            AnMessage::show('对不起，您的IP已被列入禁止的IP了，如有问题请联系电话：022-86961111');
            return false;
        }
        */
        // 解析文章的访问地址
        article_helper::rewrite_url();

        // 定义路由规则
        // @TODO 移动到配置文件中
        $rule = AnRule::getInstance();
        $rule->set('{$site=admin}/*');
        $rule->set('{$module|AnModule::isInstalled}/{$site=admin}/*');
        $rule->set('{$module|AnModule::isInstalled}/*');

        // 去掉widget的直接访问
        //$rule->set('{$proxy=proxy}/{$type=widget}/{$name}/{$func}/*');
        //$rule->set('{$module|AnModule::isInstalled}/{$proxy=proxy}/{$type=widget}/{$name}/{$func}/*');

        // 路由解析规则
        AnRouter::getInstance()->dispatch($rule);
        // 获取解析后的Url信息
        $url = AnUrl::getInstance();


        if(D_BUG) {
            //echo "\n\$url:\n";
            //var_dump($url);
        }

        // 加载site控制器
        if (!empty($url['site'])) {
            $site_controller = "{$url['site']}Controller";
            if (class_exists($site_controller)) {
                try {
                    $c = new $site_controller();
                    call_user_func(array($c, 'init'));
                } catch (Exception $e) {
                    // @TODO 改为定义不同的异常
                    AnMessage::show($e->getMessage());
                    return;
                }
            }
        }

        // 调用模块
        if (AnModule::isInstalled($url['module'])) {
            AnModule::invoke($url['module']);
        }

        // 代理解析
        if (!empty($url['proxy'])) {
            $widget_name = !empty($url['module']) ? $url['module'].'.'.$url['name'] : $url['name'];
            $params = array_merge(array('model'=>$widget_name, 'func'=>$url['func']), $_GET);
            $smarty = Response::getView();
            $message = smarty_function_widget($params, $smarty);
            if (!empty($message)) AnMessage::show($message);
            return;
        }

        $controller_path = self::getControllerFile();

        if (strtolower($url['module']) == 'api') {
            if (strpos($controller_path, 'module/api/controller/test') !== false) {
                    if (!ONDEV) {
                        exit('Not Found!');
                    }
            }
        }

        require $controller_path;

        $user_id = user_helper::get_user_id();
        if ($user_id) {
            $user_info = get_res_info('user', $user_id);
            Response::assign('user_info',  $user_info);
            // if ($user_info && $user_info['status'] != 1) {
            //     Response::set404('该用户已禁用');
            //     return;
            // }
        }

        //获取访问地址
        $currUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        // 再统一赋值
        Response::assign('url_dirs',   $url['dirs']);
        Response::assign('site',       $url['site']);
        Response::assign('module',     $url['module']);
        Response::assign('controller', $url['controller']);
        Response::assign('action',     $url['action']);
        Response::assign('user_id',    $user_id);

        Response::assign('jumpurl',    '');

        // 可以不传参，直接在方法里获取$url['controller']，传参是为兼容之前的写法
        self::$actionInstance = new Action($url['controller'], $url['action'], $url['params']);

        // 如果action不存在，且__call也不存在，则报404错误
        if (!method_exists(self::$actionInstance, $url['action']) && !method_exists(self::$actionInstance, '__call')) {
            $msg = 'Not Found';
            if (ONDEV) {
                $msg = 'Controller:'.$url['controller'].'; Action:'.$url['action'].'; Not Found';
            }
            Response::set404($msg);
            return;
        }

        // 处理__construct中的错误信息提示
        // @TODO 改成在__construct中抛出异常
        if (!empty(self::$actionInstance->error)) {
            // 错误代码对应提示信息
            // @TODO 改为定义不同的异常
            $errors = Config::get('error');
            $code = self::$actionInstance->error;
            AnMessage::show(array($errors[$code]['notice'], $errors[$code]['level'], $errors[$code]['link']));
            return;
        }

        if (!is_array($url['params'])) {
            $url['params'] = array();
        }

        $message = call_user_func_array(array(self::$actionInstance, $url['action']), $url['params']);

        if (!empty($message)) AnMessage::show($message);
    }

    /**
     * 获取控制器文件路径
     * @TODO 移动到AnRule中
     */
    private static function getControllerFile()
    {
        $defaultController = AnRouter::$defaultController;
        $url  = AnUrl::getInstance();
        $dirs = '';

        if (!empty($url['module'])) {
            // 加载模块自己的controller
            $controller_dir = MODULE_PATH."/{$url['module']}/controller";
        } else {
            $controller_dir = Config::get('controller_dir');
        }

        if (empty($url['controllerFile'])) {
            $url['controller'] = $url['controllerFile'] = $defaultController;
        }
        if (empty($url['action'])) {
            $url['action'] = 'index';
        }
        if (!empty($url['dirs'])) {
            $dirs = implode('/', $url['dirs']).'/';
        }

        $file = $controller_dir.'/'.$dirs.$url['controllerFile'].'.php';

        if (file_exists($file)) {
            return $file;
        }

        // 对应core模块里的控制器文件
        /*$file_core = MODULE_CORE.'/controller/'.$dirs.$url['controllerFile'].'.php';

        if (file_exists($file_core)) {
            // 如果core模块里存在该控制器，则采用该控制器
            return $file_core;
        }*/

        // 如果控制器不存在的话，统一走默认控制器，此时控制器和控制器文件都为默认控制器
        $params = $url['params'];
        array_unshift($params, $url['action']);
        $url['params'] = $params;
        $url['action'] = $url['controllerFile'];
        $url['controller'] = $url['controllerFile'] = $defaultController;
        $file = $controller_dir.'/'.$dirs.$url['controllerFile'].'.php';
        return $file;
    }
}

class adminController implements controllerInterface
{
    public function init()
    {
        $url        = AnUrl::getInstance();
        $user_id    = user_helper::get_user_id();
        $module     = $url['module'];
        $controller = $url['controller'];
        $action     = $url['action'];
        $res_type   = Request::getParam('res_type', 0);
        $res_name   = Request::getParam('res_name');

        if (!$user_id) {
            // 未登录跳转
            if (!empty($module)) {
//                 $callback_url = 'http://'.$_SERVER['HTTP_HOST'].'/admin/index.php'.$_SERVER['PATH_INFO'].'?'.$_SERVER['QUERY_STRING'];
                $callback_url = $_SERVER['HTTP_REFERER'];
//                 $callback_url = __FILE__;
                Response::redirect(AnUrl('admin/login?info=not_login&callback_url='.$callback_url));
                Response::flush();
            }
            return false;
        }
        // var_dump($user_id);
        // @FIXME 临时采用privilege来给菜单赋权限 START
        /*
         if (!AnAcl::hasDefinedAuth($user_id)) {
        throw new AnMessageException('您没有权限访问');
        }

        if (($module || $controller || $action != 'index')
                && !$this->check_auth($module, $controller, $action)) {
        // 访问后台非首页，无权限时
        throw new AnMessageException('您没有权限访问');
        }
        */
        // @FIXME 临时采用privilege来给菜单赋权限 END

        $admin_id = user_helper::get_user_id();

        // @FIXME 临时采用privilege来给菜单赋权限 START
        if (!user_helper::have_privilege($admin_id)) {
            throw new AnMessageException('您没有权限访问，错误1：'.__LINE__);
        }

        if ($module || $controller || $action != 'index') {
            // 非访问后台首页，限制直接访问其他未授权的菜单首页
            // @FIXME 限制不住其他未授权的菜单首页外的url直接访问
            if ($controller && $controller != 'index') {
                $filter['controller'] = $controller;
            }
            if ($action && $action != 'index') {
                $filter['action'] = $action;
            }
            if ($res_name) {
                $module_filter['res_name'] = $filter['res_name'] = $module;
            }
            $module_filter['module'] = $filter['module'] = $module;
            $module_filter['status'] = $filter['status'] = 1;

            // 先查询module。如果当前module下只有一条数据(index)，则限定该module下得所有权限。
            $is_type = 0;

            $module_number  = _model('admin_menu')->getTotal($module_filter);
            if ($module_number > 1) {
                // 如果module下面有多条数据则，除index外的所有数据单独验证权限
                if ($controller != "index" || $action != "index") {
                    $menu_id = _uri('admin_menu', $filter, 'id');
                    if ($menu_id && !$this->check_menu_auth($menu_id)) {
//                        user_helper::remember_me_expire();
                        throw new AnMessageException('您没有权限进行当前操作！');
                    }
                    $is_type = 1;
                }
            }

            // 如果验证过权限 则跳过此步骤
            if (!$is_type) {
                $menu_id = _uri('admin_menu', $module_filter, 'id');
                if ($menu_id && !$this->check_menu_auth($menu_id)) {
//                    user_helper::remember_me_expire();
                    throw new AnMessageException('您没有权限进行当前操作！');
                }
            }
        }
        // @FIXME 临时采用privilege来给菜单赋权限 END

        // 后台侧边菜单数据
        $sidebar_menu_list = array();
        $sidebar_menu_fathers = _model("admin_menu")->getList(array('parent_id'=>0, 'status'=>1, 'is_show'=>1), "ORDER BY `view_order`");
        foreach ($sidebar_menu_fathers as $k=>$v) {
            $admin_menu_children = _model("admin_menu")->getList(array('parent_id'=>$v['id'], 'status'=>1), "ORDER BY `view_order`");
            $admin_menu_children_new = array();
            foreach ($admin_menu_children as $k1=>$v1) {
            // if (!$this->check_auth($v1['module'], $v1['controller'], $v1['action'])) {
                if (!$this->check_menu_auth($v1['id'])) {
                    continue;
                }
                if (!user_helper::have_privilege()) {
                    continue;
                }
                // 是否选中
                $curr = 'curr';
                if ($v1['module']) {
                    if ($v1['module'] != $module) {
                        $curr = '';
                    }
                    $admin_res_url = $admin_res_add_url = $v1['module']."/admin";
                } else {
                    $admin_res_url = $admin_res_add_url = "admin";
                }
                if ($v1['controller']) {
                    if ($v1['controller'] != $controller) {
                        $curr = '';
                    }
                    $admin_res_url .= "/".$v1['controller'];
                    $admin_res_add_url .= "/".$v1['controller'];
                }
                if ($v1['action']) {
                    if ($v1['action'] != $action) {
                        $curr = '';
                    }
                    $admin_res_url .= "/".$v1['action'];
                }
                if ($v1['add_title']) {
                    if ($v1['add_action']) {
                        $admin_res_add_url .= "/".$v1['add_action'];
                    } else {
                        $admin_res_add_url .= "/add";
                    }
                }
                if ($v1['res_name']) {
                    if ($v1['module']) {
                        if ($v1['res_name'] != $res_name) {
                            $curr = '';
                        }
                        $admin_res_url .= "?res_name=".$v1['res_name'];
                        $admin_res_add_url .= "?res_name=".$v1['res_name'];
                    } else {
                        if ($v1['res_name'] != $res_type) {
                            $curr = '';
                        }
                        $admin_res_url .= "?res_type=".$v1['res_name'];
                        $admin_res_add_url .= "?res_type=".$v1['res_name'];
                    }
                } else {
                    if (($res_name && $v1['res_name'] != $res_name) || ($res_type && $v1['res_name'] != $res_type)) {
                        $curr = '';
                    }
                }
                $admin_menu_children_new[$k1] = $admin_menu_children[$k1];
                $admin_menu_children_new[$k1]['url'] = AnUrl($admin_res_url);
                $admin_menu_children_new[$k1]['action_url'] = AnUrl($admin_res_add_url);
                $admin_menu_children_new[$k1]['curr'] = $curr;
            }
            if ($admin_menu_children_new) {
                $sidebar_menu_list[$k] = $sidebar_menu_fathers[$k];
                $sidebar_menu_list[$k]['children'] = $admin_menu_children_new;
            }
        }
        if ($admin_id) {
            $user_info = get_res_info('user', $admin_id);
            if ($user_info && $user_info['status'] != 1) {
                Response::set404('该用户已禁用');
                return;
            }
        }

        // 统一赋值
        // 后台的$user_id实际是admin_id
        $role_id = user_helper::get_user_role_id($admin_id);
        if ($role_id == user_config::ASSISTANT) {
            // 获取订单数
            $order_num = order_helper::get_assistant_dealer_order_total_num($admin_id);
            Response::assign('order_num', $order_num);
        }

        // 写入后台操作日志
        admin_log_helper::write_admin_log($module, $controller, $action, $_REQUEST);

        Response::assign('user_id', $admin_id);
        // Response::assign('role_id', $role_id);
        Response::assign("sidebar_menu_list",  $sidebar_menu_list);

        return true;
    }

    /**
     * 判断是否有后台menu显示的权限
     * @param 后台菜单的id $admin_menu_id
     * @return bool
     */
    private function check_menu_auth($admin_menu_id)
    {
//         $admin_id = user_helper::get_admin_id();
//         $role_ids = user_helper::get_user_role_ids($admin_id);
//         foreach ($role_ids as $v) {
//             $privilege = _uri('role', $v, 'privilege');
//             // 超级管理员
//             if ($privilege == '*') {
//                 return true;
//             }
//             $privileges = explode(',', $privilege);
//             if (in_array($admin_menu_id, $privileges)) {
//                 return true;
//             }
//         }
//         return false;
           $admin_id = user_helper::get_admin_id();
           $role_ids = user_helper::get_user_role_ids($admin_id);
           foreach ($role_ids as $v) {
               $privilege = _uri('role', $v, 'privilege');
               // 超级管理员
               if ($privilege == '*') {
                   return true;
               }
               $privileges = explode(',', $privilege);
               if ($privileges) {
                   foreach ($privileges as $key => $val) {
                       $admin_menu_info = _uri('admin_menu', $val);
                       if ($val == $admin_menu_id) {
                           return true;
                       }
                       if ($admin_menu_info['parent_id'] == $admin_menu_id) {
                           return true;
                       }
                   }
               }
           }

           return false;
    }

}

interface controllerInterface
{
    public function init();
}
?>